import { config } from '@/config'

// 创建基础请求函数
export const request = async (url: string, options: RequestInit = {}) => {
  const fullUrl = url.startsWith('http') ? url : `${config.apiBaseUrl}${url}`
  
  const defaultOptions: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  try {
    const response = await fetch(fullUrl, defaultOptions)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await response.json()
  } catch (error) {
    console.error('Request failed:', error)
    throw error
  }
}

// GET请求
export const get = (url: string, options?: RequestInit) => {
  return request(url, { method: 'GET', ...options })
}

// POST请求
export const post = (url: string, data?: any, options?: RequestInit) => {
  return request(url, {
    method: 'POST',
    body: data ? JSON.stringify(data) : undefined,
    ...options,
  })
}

// PUT请求
export const put = (url: string, data?: any, options?: RequestInit) => {
  return request(url, {
    method: 'PUT',
    body: data ? JSON.stringify(data) : undefined,
    ...options,
  })
}

// DELETE请求
export const del = (url: string, options?: RequestInit) => {
  return request(url, { method: 'DELETE', ...options })
}

// 导出统一的 http 对象
export const http = {
  get: (url: string, options?: any) => {
    const { params, ...restOptions } = options || {}
    // 处理查询参数
    if (params) {
      const searchParams = new URLSearchParams()
      Object.keys(params).forEach(key => {
        if (params[key] !== undefined && params[key] !== null) {
          searchParams.append(key, params[key])
        }
      })
      const queryString = searchParams.toString()
      url = queryString ? `${url}?${queryString}` : url
    }
    return get(url, restOptions)
  },
  post,
  put,
  delete: del
} 